<template>
  <div class="flex">
    <div class="item" v-for="(item, index) in url_list">
      <img :src="item" alt="" />
      <i class="el-icon-error" @click="delect(index)"></i>
    </div>
    <div class="upload" v-if="maxlength > url_list.length">
      <i class="el-icon-plus avatar-uploader-icon"></i>
      <input type="file" name="singleFile" @change="selectFile" multiple />
    </div>
  </div>
</template>
<script>
import ossApi from "@/API/ossApi";
import OSS from "ali-oss";
export default {
  props: {
    img_url: {
      type: String,
      default: "",
    },
    maxlength: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      options: {},
      url_list: [],
    };
  },
  mounted() {
    if(this.img_url){
      this.url_list = this.url_list.concat(this.img_url);
    }
    this.getAliToken();
  },
  methods: {
    async getAliToken(file, filename) {
      let { data } = await ossApi.getAliToken();
      this.options = data;
    },
    selectFile(e) {
      let files = e.target.files;
      let client = new OSS({
        accessKeyId: this.options.AccessKeyId,
        accessKeySecret: this.options.AccessKeySecret,
        stsToken: this.options.SecurityToken,
        region: this.options.region,
        bucket: this.options.bucket,
        endpoint: "https://oss.li586543.cn",
        cname: true,
      });
      this.uploadImg(files,client);
    },
    async uploadImg(files,client,index = 0){
      let length = this.maxlength
      if(index < length && this.url_list.length < this.maxlength){
        let { res, url } = await client.put(files[index].name, files[index]);
        if (res.status == 200) {
          this.url_list = this.url_list.concat(url);
          index ++ 
          this.uploadImg(files,client,index)
        }else{
          index ++ 
          this.uploadImg(files,client,index)
        }
      }else{
        this.$emit('getImgs',this.url_list)
        return
      }
    },
    delect(index) {
      this.url_list.splice(index, 1);
    },
  },
};
</script>
<style scoped>
.flex{
  flex-wrap: wrap;
  padding-top: 10px;
}
.item {
  width: 200px;
  height: 150px;
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
  font-size: 22px;
  position: relative;
  transition: all 0.5s linear;
}
.item img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 6px;
}
.item i {
  position: absolute;
  top: -11px;
  right: -11px;
}
.upload {
  width: 200px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  font-size: 28px;
  position: relative;
  text-align: center;
}
.upload:hover {
  border-color: #409eff;
}
.upload i {
  line-height: 150px;
}
.upload input {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
}
</style>